<template>
  <el-card class="box">
    <div class="top">
      <span style="font-size: 25px; color: #203857; margin-right: 10px"
        >个人申请管理</span
      >
    </div>
    <el-form :model="selectForm" :inline="true">
      <el-form-item label="通知名">
        <el-input v-model="selectForm.title" placeholder="请输入通知名" />
      </el-form-item>
      <el-form-item label="通知状态">
        <el-select
          v-model="selectForm.status"
          placeholder="请选择通知状态"
          style="width: 200px"
        >
          <el-option label="待审核" :value="0"></el-option>
          <el-option label="已通过" :value="1"></el-option>
          <el-option label="未通过" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getNoticeList" plain
          ><el-icon><ZoomIn /></el-icon>筛选</el-button
        >
        <el-button @click="refreshList">清除筛选</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="datalist"
      stripe
      height="350px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column prop="createTime" label="申请时间" align="center" />
      <el-table-column prop="noticeTitle" label="通知名" align="center" />
      <el-table-column prop="deadLine" label="截止时间" align="center" />
      <el-table-column prop="status" label="申请状态" align="center">
        <template #default="{ row }">
          <span :style="{ color: statusColor[row.status] }">{{
            statusText[row.status]
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200px">
        <template #default="{ row }">
          <div class="operation-buttons">
            <el-upload
              :disabled="isDeadlinePassed(row.deadLine, row.status)"
              :ref="
                (el) => {
                  if (el) uploadRefs[row.id] = el;
                }
              "
              :auto-upload="false"
              :show-file-list="false"
              :limit="1"
              @change="handleFileUpload($event, row.noticeId)"
              @exceed="handleExceed"
            >
              <el-button
                type="primary"
                size="small"
                :disabled="isDeadlinePassed(row.deadLine, row.status)"
                >重新提交</el-button
              >
            </el-upload>
            <el-button
              :disabled="row.status !== 2"
              type="warning"
              size="small"
              @click="openRejectionInfo(row)"
            >
              查看驳回原因
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 驳回原因弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%">
      <div style="margin: 20px; font-size: large">{{ rejectionReason }}</div>
      <img
        v-if="rejectionImage"
        :src="rejectionImage"
        alt="驳回图片"
        style="max-width: 100%; max-height: 100%"
      />
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  GetUserApplication,
  uploadFile as uploadFileAPI,
} from "../../api/announcement";
import { useUserStore } from "@/store";

const pageSize = ref(3);
const currentPage = ref(1);
const userStore = useUserStore();
const selectForm = ref({
  title: "",
  status: null,
  studentName: userStore.userVO.userName,
  studentClass: userStore.userVO.userClass,
});

const total = ref(0);
const datalist = ref([]);
const multipleSelection = ref([]);
const uploadRefs = ref({}); // 存储每个申请项的上传组件引用

const statusText = computed(() => ({
  0: "待审核",
  1: "已通过",
  2: "被驳回",
}));

const statusColor = computed(() => ({
  0: "#409EFF", // 待审核颜色
  1: "#008000", // 已通过颜色
  2: "#FF0000", // 未通过颜色
}));

const refreshList = () => {
  selectForm.value = {};
};

const getApplications = async () => {
  const res = await GetUserApplication(
    currentPage.value,
    pageSize.value,
    selectForm.value
  );
  datalist.value = res.data;
  total.value = res.count;
};

const handleSelectionChange = (selection) => {
  multipleSelection.value = selection.map((item) => item.id);
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  getApplications();
};

const handleCurrentChange = (num) => {
  currentPage.value = num;
  getApplications();
};

onMounted(() => {
  getApplications();
});

const getNoticeList = async () => {
  getApplications();
};

const showResubmitButton = computed(() => {
  return datalist.value.some((item) => item.status === 2);
});

const isDeadlinePassed = (deadline, status) => {
  // console.log(deadline + status);
  const now = new Date();
  const deadLineDate = new Date(deadline);

  if (status === 2) return false;
  return now > deadLineDate || status === 1;
};
const handleFileUpload = async (event, id) => {
  const file = event.raw;
  if (!file) {
    alert("请选择一个文件");
    return;
  }

  try {
    console.log("重新提交的文件" + file);
    const response = await uploadFileAPI(file, id);
    ElMessage.success("文件上传成功");

    // 清除文件输入框中的文件
    if (uploadRefs.value[id]) {
      uploadRefs.value[id].clearFiles();
    }

    getApplications();
  } catch (error) {
    ElMessage.error("文件上传失败");
  }
};

const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `当前限制为只能上传 1 个文件。这次选择了 ${files.length} 个文件，共选择了 ${
      files.length + uploadFiles.length
    } 个文件`
  );
};

// 弹出层相关逻辑
const dialogVisible = ref(false);
const dialogTitle = ref("驳回原因");
const rejectionReason = ref("");
const rejectionImage = ref("");

const openRejectionInfo = (row) => {
  dialogTitle.value = "驳回原因";
  rejectionReason.value = row.rejectReason || "无具体原因";
  rejectionImage.value = row.rejectImage || "";
  dialogVisible.value = true;
};
</script>

<style scoped lang="scss">
.box {
  padding: 15px;
  .el-table {
    margin-bottom: 2vh;
  }
}
.top {
  display: flex;
  width: 100%;
  height: 50px;
  line-height: 50px;
  align-items: center;
  margin-bottom: 15px;
}

.operation-buttons {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
</style>
